<template>
  <div class="environment-monitoring">
    <div class="page-header">
      <h2>环境监控管理</h2>
      <Space>
        <Button @click="refreshDevices">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新数据
        </Button>
        <Button type="primary" @click="showAddDeviceModal = true">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加设备
        </Button>
      </Space>
    </div>

    <!-- 环境监控统计 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="监控设备"
          :value="statistics.totalDevices"
          :change="statistics.totalChange"
          icon="ant-design:cloud-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="在线设备"
          :value="statistics.onlineDevices"
          :change="statistics.onlineChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="异常设备"
          :value="statistics.abnormalDevices"
          :change="statistics.abnormalChange"
          icon="ant-design:warning-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="今日告警"
          :value="statistics.todayAlerts"
          :change="statistics.alertsChange"
          icon="ant-design:alert-outlined"
          color="#f5222d"
        />
      </Col>
    </Row>

    <!-- 实时环境数据 -->
    <Row :gutter="16" class="environment-panel">
      <Col :span="8">
        <Card title="温湿度监控" class="environment-card">
          <div class="environment-content">
            <div class="data-summary">
              <div class="data-item">
                <span class="data-label">平均温度</span>
                <span class="data-value"
                  >{{ environmentData.temperature }}°C</span
                >
              </div>
              <div class="data-item">
                <span class="data-label">平均湿度</span>
                <span class="data-value">{{ environmentData.humidity }}%</span>
              </div>
              <div class="data-item">
                <span class="data-label">舒适度</span>
                <span class="data-value">{{ environmentData.comfort }}</span>
              </div>
            </div>
            <div class="data-chart">
              <div class="chart-placeholder">
                <IconifyIcon
                  icon="ant-design:line-chart-outlined"
                  class="chart-icon"
                />
                <p>温湿度趋势图</p>
              </div>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="8">
        <Card title="空气质量监测" class="environment-card">
          <div class="environment-content">
            <div class="data-summary">
              <div class="data-item">
                <span class="data-label">PM2.5</span>
                <span class="data-value">{{ environmentData.pm25 }} μg/m³</span>
              </div>
              <div class="data-item">
                <span class="data-label">PM10</span>
                <span class="data-value">{{ environmentData.pm10 }} μg/m³</span>
              </div>
              <div class="data-item">
                <span class="data-label">空气质量</span>
                <span class="data-value">{{ environmentData.airQuality }}</span>
              </div>
            </div>
            <div class="data-chart">
              <div class="chart-placeholder">
                <IconifyIcon
                  icon="ant-design:line-chart-outlined"
                  class="chart-icon"
                />
                <p>空气质量趋势图</p>
              </div>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="8">
        <Card title="光照监控" class="environment-card">
          <div class="environment-content">
            <div class="data-summary">
              <div class="data-item">
                <span class="data-label">光照强度</span>
                <span class="data-value">{{ environmentData.light }} lux</span>
              </div>
              <div class="data-item">
                <span class="data-label">紫外线</span>
                <span class="data-value">{{ environmentData.uv }} mW/cm²</span>
              </div>
              <div class="data-item">
                <span class="data-label">光照状态</span>
                <span class="data-value">{{
                  environmentData.lightStatus
                }}</span>
              </div>
            </div>
            <div class="data-chart">
              <div class="chart-placeholder">
                <IconifyIcon
                  icon="ant-design:line-chart-outlined"
                  class="chart-icon"
                />
                <p>光照强度趋势图</p>
              </div>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 设备列表 -->
    <Card title="环境监控设备" class="devices-list-card">
      <div class="list-header">
        <Form layout="inline" :model="searchForm" class="search-form">
          <FormItem label="设备名称">
            <Input
              v-model:value="searchForm.name"
              placeholder="请输入设备名称"
              allow-clear
            />
          </FormItem>
          <FormItem label="设备类型">
            <Select
              v-model:value="searchForm.type"
              placeholder="请选择类型"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="temperature">温湿度传感器</SelectOption>
              <SelectOption value="air">空气质量传感器</SelectOption>
              <SelectOption value="light">光照传感器</SelectOption>
              <SelectOption value="noise">噪音传感器</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="设备状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="online">在线</SelectOption>
              <SelectOption value="offline">离线</SelectOption>
              <SelectOption value="abnormal">异常</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="安装位置">
            <Input
              v-model:value="searchForm.location"
              placeholder="请输入安装位置"
              allow-clear
            />
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleSearch">
                <IconifyIcon icon="ant-design:search-outlined" />
                搜索
              </Button>
              <Button @click="handleReset">
                <IconifyIcon icon="ant-design:reload-outlined" />
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>
      <Table
        :columns="columns"
        :data-source="filteredDevices"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="device-info">
              <div class="device-name">{{ record.name }}</div>
              <div class="device-id">ID: {{ record.deviceId }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'currentValue'">
            <div class="value-info">
              <div class="value-display">{{ record.currentValue }}</div>
              <div class="value-unit">{{ getUnitText(record.type) }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'threshold'">
            <div class="threshold-info">
              <span class="threshold-min">{{ record.thresholdMin }}</span>
              <span class="threshold-separator">-</span>
              <span class="threshold-max">{{ record.thresholdMax }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'lastUpdate'">
            <div class="update-info">
              <span class="update-time">{{ record.lastUpdate }}</span>
              <span class="update-status" :class="record.status">
                {{ getUpdateStatusText(record.status) }}
              </span>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDevice(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="viewHistory(record)">
                历史
              </Button>
              <Button type="link" size="small" @click="editDevice(record)">
                编辑
              </Button>
              <Button
                type="link"
                size="small"
                @click="configureThreshold(record)"
              >
                阈值
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 环境告警 -->
    <Card title="环境告警" class="alerts-card">
      <div class="alerts-list">
        <div
          v-for="alert in environmentAlerts"
          :key="alert.id"
          class="alert-item"
          :class="alert.level"
        >
          <div class="alert-icon">
            <IconifyIcon :icon="getAlertIcon(alert.level)" />
          </div>
          <div class="alert-content">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-desc">{{ alert.description }}</div>
            <div class="alert-time">{{ alert.time }}</div>
          </div>
          <div class="alert-actions">
            <Button type="link" size="small" @click="handleAlert(alert)">
              处理
            </Button>
          </div>
        </div>
      </div>
    </Card>

    <!-- 添加设备弹窗 -->
    <Modal
      v-model:open="showAddDeviceModal"
      title="添加环境监控设备"
      width="700px"
      @ok="handleSaveDevice"
      @cancel="handleCancelDevice"
    >
      <Form
        ref="deviceFormRef"
        :model="deviceForm"
        :rules="deviceRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="设备名称" name="name">
              <Input
                v-model:value="deviceForm.name"
                placeholder="请输入设备名称"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="设备类型" name="type">
              <Select
                v-model:value="deviceForm.type"
                placeholder="请选择设备类型"
              >
                <SelectOption value="temperature">温湿度传感器</SelectOption>
                <SelectOption value="air">空气质量传感器</SelectOption>
                <SelectOption value="light">光照传感器</SelectOption>
                <SelectOption value="noise">噪音传感器</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="设备型号" name="model">
              <Input
                v-model:value="deviceForm.model"
                placeholder="请输入设备型号"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="设备厂商" name="manufacturer">
              <Input
                v-model:value="deviceForm.manufacturer"
                placeholder="请输入设备厂商"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="安装位置" name="location">
              <Input
                v-model:value="deviceForm.location"
                placeholder="请输入安装位置"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="IP地址" name="ipAddress">
              <Input
                v-model:value="deviceForm.ipAddress"
                placeholder="请输入IP地址"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="阈值下限" name="thresholdMin">
              <Input
                v-model:value="deviceForm.thresholdMin"
                placeholder="请输入阈值下限"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="阈值上限" name="thresholdMax">
              <Input
                v-model:value="deviceForm.thresholdMax"
                placeholder="请输入阈值上限"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="设备描述" name="description">
          <Textarea
            v-model:value="deviceForm.description"
            placeholder="请输入设备描述"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';

// 状态管理
const loading = ref(false);
const showAddDeviceModal = ref(false);
const isEdit = ref(false);

// 表单引用
const deviceFormRef = ref();

// 统计数据
const statistics = reactive({
  totalDevices: 18,
  totalChange: 2,
  onlineDevices: 16,
  onlineChange: 1,
  abnormalDevices: 2,
  abnormalChange: -1,
  todayAlerts: 5,
  alertsChange: 1,
});

// 环境数据
const environmentData = reactive({
  temperature: 24.5,
  humidity: 65,
  comfort: '舒适',
  pm25: 35,
  pm10: 75,
  airQuality: '良好',
  light: 850,
  uv: 2.5,
  lightStatus: '正常',
});

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
  location: '',
});

// 设备表单
const deviceForm = reactive({
  name: '',
  type: '',
  model: '',
  manufacturer: '',
  location: '',
  ipAddress: '',
  thresholdMin: '',
  thresholdMax: '',
  description: '',
});

// 表单验证规则
const deviceRules = {
  name: [{ required: true, message: '请输入设备名称' }],
  type: [{ required: true, message: '请选择设备类型' }],
  location: [{ required: true, message: '请输入安装位置' }],
  ipAddress: [{ required: true, message: '请输入IP地址' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 环境告警数据
const environmentAlerts = ref([
  {
    id: 1,
    level: 'critical',
    title: '温度异常',
    description: '101房间温度过高，当前温度28°C，超过阈值',
    time: '3分钟前',
  },
  {
    id: 2,
    level: 'warning',
    title: '空气质量下降',
    description: '大厅PM2.5浓度超标，建议开启空气净化',
    time: '8分钟前',
  },
  {
    id: 3,
    level: 'info',
    title: '光照不足',
    description: '205房间光照强度不足，建议开启照明',
    time: '15分钟前',
  },
]);

// 设备数据
const devices = ref([
  {
    id: 1,
    name: '温湿度传感器-101',
    deviceId: 'TEMP001',
    type: 'temperature',
    status: 'online',
    currentValue: '24.5°C / 65%',
    thresholdMin: '18°C / 40%',
    thresholdMax: '26°C / 70%',
    lastUpdate: '2024-01-19 15:30',
    model: 'TH-100',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.101',
  },
  {
    id: 2,
    name: '空气质量传感器-大厅',
    deviceId: 'AIR001',
    type: 'air',
    status: 'online',
    currentValue: 'PM2.5: 35',
    thresholdMin: '0',
    thresholdMax: '75',
    lastUpdate: '2024-01-19 15:30',
    model: 'AQ-200',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.102',
  },
  {
    id: 3,
    name: '光照传感器-205',
    deviceId: 'LIGHT001',
    type: 'light',
    status: 'abnormal',
    currentValue: '450 lux',
    thresholdMin: '500',
    thresholdMax: '2000',
    lastUpdate: '2024-01-19 15:25',
    model: 'LS-100',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.103',
  },
  {
    id: 4,
    name: '噪音传感器-走廊',
    deviceId: 'NOISE001',
    type: 'noise',
    status: 'online',
    currentValue: '45 dB',
    thresholdMin: '0',
    thresholdMax: '60',
    lastUpdate: '2024-01-19 15:30',
    model: 'NS-100',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.104',
  },
]);

// 表格列定义
const columns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '设备状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '当前数值',
    dataIndex: 'currentValue',
    key: 'currentValue',
    width: 150,
  },
  {
    title: '阈值范围',
    dataIndex: 'threshold',
    key: 'threshold',
    width: 150,
  },
  {
    title: '最后更新',
    dataIndex: 'lastUpdate',
    key: 'lastUpdate',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 过滤后的设备数据
const filteredDevices = computed(() => {
  let result = devices.value;

  if (searchForm.name) {
    result = result.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase()),
    );
  }

  if (searchForm.type) {
    result = result.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.location) {
    result = result.filter((item) =>
      item.location.toLowerCase().includes(searchForm.location.toLowerCase()),
    );
  }

  return result;
});

// 类型相关函数
const getTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    temperature: 'blue',
    air: 'green',
    light: 'orange',
    noise: 'purple',
  };
  return colors[type] || 'default';
};

const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    temperature: '温湿度传感器',
    air: '空气质量传感器',
    light: '光照传感器',
    noise: '噪音传感器',
  };
  return texts[type] || type;
};

// 状态相关函数
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    online: 'green',
    offline: 'red',
    abnormal: 'orange',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '在线',
    offline: '离线',
    abnormal: '异常',
  };
  return texts[status] || status;
};

const getUpdateStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '正常',
    offline: '离线',
    abnormal: '异常',
  };
  return texts[status] || status;
};

// 单位相关函数
const getUnitText = (type: string) => {
  const units: Record<string, string> = {
    temperature: '°C/%',
    air: 'μg/m³',
    light: 'lux',
    noise: 'dB',
  };
  return units[type] || '';
};

// 告警相关函数
const getAlertIcon = (level: string) => {
  const icons: Record<string, string> = {
    critical: 'ant-design:close-circle-outlined',
    warning: 'ant-design:warning-outlined',
    info: 'ant-design:info-circle-outlined',
  };
  return icons[level] || 'ant-design:info-circle-outlined';
};

// 事件处理函数
const refreshDevices = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    message.success('设备数据刷新完成');
  }, 1000);
};

const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: '',
    location: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSaveDevice = async () => {
  try {
    await deviceFormRef.value.validate();
    if (isEdit.value) {
      message.success('设备信息更新成功');
    } else {
      message.success('设备添加成功');
    }
    showAddDeviceModal.value = false;
    resetDeviceForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancelDevice = () => {
  showAddDeviceModal.value = false;
  resetDeviceForm();
};

const viewDevice = (record: any) => {
  message.info(`查看设备详情: ${record.name}`);
};

const viewHistory = (record: any) => {
  message.info(`查看历史记录: ${record.name}`);
};

const editDevice = (record: any) => {
  isEdit.value = true;
  Object.assign(deviceForm, record);
  showAddDeviceModal.value = true;
};

const configureThreshold = (record: any) => {
  message.info(`配置阈值: ${record.name}`);
};

const handleAlert = (alert: any) => {
  message.success(`告警"${alert.title}"已处理`);
};

const resetDeviceForm = () => {
  Object.assign(deviceForm, {
    name: '',
    type: '',
    model: '',
    manufacturer: '',
    location: '',
    ipAddress: '',
    thresholdMin: '',
    thresholdMax: '',
    description: '',
  });
  isEdit.value = false;
};

onMounted(() => {
  // 初始化数据
  pagination.total = devices.value.length;
});
</script>

<style scoped>
.environment-monitoring {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.environment-panel {
  margin-bottom: 24px;
}

.environment-card {
  height: 300px;
}

.environment-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.data-summary {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.data-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.data-label {
  font-size: 14px;
  color: #666;
}

.data-value {
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
}

.data-chart {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  color: #999;
  text-align: center;
}

.chart-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.devices-list-card {
  margin-bottom: 24px;
}

.list-header {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.device-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.device-name {
  font-weight: 500;
  color: #1890ff;
  cursor: pointer;
}

.device-name:hover {
  text-decoration: underline;
}

.device-id {
  font-size: 12px;
  color: #999;
}

.value-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.value-display {
  font-weight: 500;
  color: #1890ff;
}

.value-unit {
  font-size: 12px;
  color: #999;
}

.threshold-info {
  display: flex;
  gap: 4px;
  align-items: center;
}

.threshold-min,
.threshold-max {
  font-size: 12px;
  color: #666;
}

.threshold-separator {
  font-size: 12px;
  color: #999;
}

.update-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.update-time {
  font-size: 12px;
  color: #666;
}

.update-status {
  font-size: 12px;
  font-weight: 500;
}

.update-status.online {
  color: #52c41a;
}

.update-status.offline {
  color: #f5222d;
}

.update-status.abnormal {
  color: #faad14;
}

.alerts-card {
  margin-bottom: 16px;
}

.alerts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.alert-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  padding: 12px;
  border-radius: 6px;
}

.alert-item.critical {
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
}

.alert-item.warning {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
}

.alert-item.info {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
}

.alert-icon {
  margin-top: 2px;
  font-size: 16px;
}

.alert-item.critical .alert-icon {
  color: #f5222d;
}

.alert-item.warning .alert-icon {
  color: #faad14;
}

.alert-item.info .alert-icon {
  color: #52c41a;
}

.alert-content {
  flex: 1;
}

.alert-title {
  margin-bottom: 4px;
  font-weight: 500;
}

.alert-desc {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.alert-time {
  font-size: 12px;
  color: #999;
}

.alert-actions {
  display: flex;
  align-items: center;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
